package com.cxh.rmsq.ui.activity.self

import android.annotation.SuppressLint
import android.app.Dialog
import android.content.Context
import android.database.Cursor
import android.net.Uri
import android.os.Bundle
import android.provider.MediaStore
import android.text.TextUtils
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.ImageView
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProviders
import com.cxh.rmsq.R
import com.cxh.rmsq.im.IMManager
import com.cxh.rmsq.model.Resource2
import com.cxh.rmsq.model.Result2
import com.cxh.rmsq.model.Status
import com.cxh.rmsq.ui.activity.TitleBaseActivity
import com.cxh.rmsq.utils.CustomPermissionUtil
import com.cxh.rmsq.utils.GlideEngine
import com.cxh.rmsq.utils.MyGridView
import com.cxh.rmsq.utils.RegexUtils
import com.cxh.rmsq.utils.loadImage
import com.cxh.rmsq.viewmodel.UserInfoViewModel
import com.hjq.shape.view.ShapeEditText
import com.luck.picture.lib.basic.PictureSelector
import com.luck.picture.lib.config.PictureMimeType
import com.luck.picture.lib.config.SelectMimeType
import com.luck.picture.lib.config.SelectModeConfig
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.interfaces.OnPermissionsInterceptListener
import com.luck.picture.lib.interfaces.OnRequestPermissionListener
import com.luck.picture.lib.interfaces.OnResultCallbackListener
import com.luck.picture.lib.permissions.PermissionChecker
import com.luck.picture.lib.permissions.PermissionConfig
import com.luck.picture.lib.permissions.PermissionResultCallback
import com.xuexiang.xui.widget.imageview.RadiusImageView
import java.util.Arrays

/**
 * 账号申诉
 */
class AccountCompaintActivity : TitleBaseActivity() {

    private val content: ShapeEditText by lazy { findViewById<ShapeEditText>(R.id.set_content) }
    private val email: ShapeEditText by lazy { findViewById<ShapeEditText>(R.id.set_email) }
    private val recyclerView: MyGridView by lazy { findViewById<MyGridView>(R.id.recyclerView) }
    private val tvSubmit: TextView by lazy { findViewById<TextView>(R.id.tv_submit) }

    private var mAdapter = PicAdapter()
    private var mData = mutableListOf<String>() //图片
    private var mDataPath = mutableListOf<String>() //选中后返回的
    var moreImgPath = ""
    var morePathList = mutableListOf<String>()
    private var userInfoViewModel: UserInfoViewModel? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_account_compaint)
        titleBar.tvTitle.text = "账号申诉"

        initData()
        recyclerView.adapter = mAdapter
        recyclerView.setOnItemClickListener { parent, view, position, id ->
            Log.i("posi", "${position} ** ${parent.childCount - 1}")
            if (position == parent.childCount - 1) {
                //addMainPicture()
//                SelectUpdatePic()
                transferPhoto()
            }
        }
    }

    private fun initData() {
        val brand = android.os.Build.BRAND
        val model = android.os.Build.MODEL
        val manufacturer = android.os.Build.MANUFACTURER
        val device = "$brand $model"
        Log.e("device", brand + "__" + model + "__" + manufacturer)
        userInfoViewModel =
            ViewModelProviders.of(this).get<UserInfoViewModel>(UserInfoViewModel::class.java)

        userInfoViewModel!!.accountAppeal()
            .observe(this@AccountCompaintActivity) { resource: Result2<String?> ->
                dismissLoadingDialog()
                if (resource.code == 200 && resource.data != null) {
                    finish()
                    showToast("提交成功")
                } else {
                    showToast(resource.msg)
                }
            }

        tvSubmit.setOnClickListener {
            if (isFastClick){
                return@setOnClickListener
            }
            if (TextUtils.isEmpty(content.text.toString().trim())) {
                showToast("请填写申诉理由")
                return@setOnClickListener
            }
            if (TextUtils.isEmpty(email.text.toString().trim())) {
                showToast("请填写邮箱")
                return@setOnClickListener
            }
            if (!RegexUtils.checkEmail(email.text.toString().trim())) {
                showToast("请填写正确的邮箱")
                return@setOnClickListener
            }
            Log.e("img", moreImgPath)
            showLoadingDialog("")
            userInfoViewModel!!.accountAppeal(
                device,
                IMManager.getInstance().getCurrentId(),
                content.text.toString().trim(),
                email.text.toString().trim(),
                0,
                moreImgPath
            )

        }
    }

    public fun transferPhoto() {
//        pictureSelector = PictureSelector.create(this)
//        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
//            // 显示对话框告知用户权限使用目的
//            val builder: AlertDialog.Builder = AlertDialog.Builder(this)
//            builder.setTitle("权限申请")
//                .setMessage("我们需要访问您的相机、存储权限，以便于图片上传、好友间发送照片以及实名认证等操作")
//                .setPositiveButton("允许",
//                    DialogInterface.OnClickListener { dialog, which ->
//                        AppPermissionUtil.requestPermissions(this@AccountCompaintActivity,
//                            arrayOf<String>(
//                                Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE
//                            ),
//                            object : AppPermissionUtil.OnPermissionListener {
//                                override fun onPermissionGranted() {
//                                    picSelect()
//                                }
//
//                                override fun onPermissionDenied() {
//
//                                }
//
//                            })
//                    })
//                .setNegativeButton(
//                    "拒绝",
//                    DialogInterface.OnClickListener { dialog, which ->
//                        // 用户拒绝权限申请
//                    })
//                .show()
//        } else {
            // 已获得权限，执行相关操作
            picSelect()
//        }
    }

    private fun picSelect() {
        PictureSelector.create(this)
            .openGallery(SelectMimeType.ofImage()) //全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
            .setImageEngine(GlideEngine.createGlideEngine())// 图片加载引擎 需要 implements ImageEngine接口
            .setMaxSelectNum(3 - morePathList.size) // 最大图片选择数量 int
            .setMinSelectNum(0) // 最小选择数量 int
            .setImageSpanCount(4) // 每行显示个数 int
            .setSelectionMode(SelectModeConfig.MULTIPLE) // 多选 or 单选 PictureConfig.MULTIPLE or PictureConfig.SINGLE
            .isDisplayCamera(true) // 是否显示拍照按钮 true or false
            .setCameraImageFormat(PictureMimeType.PNG) // 拍照保存图片格式后缀,默认jpeg
//            .isZoomAnim(true) // 图片列表点击 缩放效果 默认true
//            .isEnableCrop(true)
//            .isCompress(true)
            .isGif(false)
            .isMaxSelectEnabledMask(true)
            .isOriginalControl(true)
            .isPageStrategy(true)
//            .circleDimmedLayer(false) // 是否圆形裁剪 true or false
//            .comp(100) // 小于100kb的图片不压缩
//            .synOrAsy(true) //同步true或异步false 压缩 默认同步
//            .isDragFrame(false) // 是否可拖动裁剪框(固定)
            .setPermissionsInterceptListener(object : OnPermissionsInterceptListener {
                override fun requestPermission(
                    fragment: Fragment,
                    permissionArray: Array<String>,
                    call: OnRequestPermissionListener
                ) {
                    val permissionInfoDialog = Dialog(fragment.requireActivity())
                    //应用上架要求添加权限使用说明
                    var permissionInfoTitle = ""
                    var permissionInfoContent = ""
                    if (Arrays.equals(
                            permissionArray,
                            PermissionConfig.getReadPermissionArray(
                                fragment.context,
                                SelectMimeType.ofImage()
                            )
                        )
                    ) {
                        permissionInfoTitle =
                            resources.getString(R.string.permission_info_title_storage)
                        permissionInfoContent =
                            resources.getString(R.string.permission_info_content_storage)
                    } else if (Arrays.equals(permissionArray, PermissionConfig.CAMERA)) {
                        permissionInfoTitle =
                            resources.getString(R.string.permission_info_title_camera)
                        permissionInfoContent =
                            resources.getString(R.string.permission_info_content_camera)
                    }
                    if (!TextUtils.isEmpty(permissionInfoTitle) && !TextUtils.isEmpty(
                            permissionInfoContent
                        )
                    ) {
                        CustomPermissionUtil.showPermissionInfo(
                            fragment.activity,
                            permissionInfoDialog,
                            permissionInfoTitle,
                            permissionInfoContent
                        )
                    }

                    //此处使用图片选择框架的权限申请
                    PermissionChecker.getInstance().requestPermissions(
                        fragment,
                        permissionArray,
                        object : PermissionResultCallback {
                            override fun onGranted() {
                                permissionInfoDialog.dismiss()
                                call.onCall(permissionArray, true)
                            }

                            override fun onDenied() {
                                permissionInfoDialog.dismiss()
                                call.onCall(permissionArray, false)
                            }
                        })
                }

                override fun hasPermissions(
                    fragment: Fragment,
                    permissionArray: Array<String>
                ): Boolean {
                    return PermissionChecker.isCheckSelfPermission(
                        fragment.context,
                        permissionArray
                    )
                }
            })
            .setPermissionDeniedListener { fragment, permissionArray, requestCode, call -> //权限拒绝，弹出去设置弹窗，点击设置跳转到应用权限系统设置页面
                var permissionSetContent = ""
                if (Arrays.equals(
                        permissionArray,
                        PermissionConfig.getReadPermissionArray(
                            fragment.context,
                            SelectMimeType.ofImage()
                        )
                    )
                ) {
                    permissionSetContent = resources.getString(R.string.permission_set_storage)
                } else if (Arrays.equals(permissionArray, PermissionConfig.CAMERA)) {
                    permissionSetContent = resources.getString(R.string.permission_set_camera)
                }
                if (!TextUtils.isEmpty(permissionSetContent)) {
                    CustomPermissionUtil.showPermissionSet(
                        fragment.activity,
                        permissionSetContent,
                        ArrayList(Arrays.asList(*permissionArray))
                    ) { call.onCall(true) }
                }
            }
            .forResult(object : OnResultCallbackListener<LocalMedia> {
                @SuppressLint("SuspiciousIndentation")
                override fun onResult(result: java.util.ArrayList<LocalMedia>?) {
                    if (result != null) {
                        val images: MutableList<String> = ArrayList()
                        for (localMedia in result) {
                            var path = localMedia.realPath.toString()

//                            localMedia.isCut()
//                            path = localMedia.cutPath
                            if (path.contains("content://")) {
                                val imgPath = getPath(path)
                                images.add(imgPath)
                            } else {
                                images.add(path)
                            }
                        }

                        var i = 0
                        mDataPath.clear()
                        while (i < images.size) {
                            var path = ""
                            path = images[i]
                            Log.i("path123", path)
                            mData.add(path)
                            mDataPath.add(path)
                            i++
                        }
                        mAdapter.setData()
                        for (j in 0 until mDataPath.size) {
                            userInfoViewModel!!.uploadImg(mDataPath[j])
                            userInfoViewModel!!.upload()
                                .observe(this@AccountCompaintActivity) { resource: Resource2<String?> ->
                                    if (resource.status == Status.SUCCESS && resource.data != null) {
                                        if (moreImgPath == "") {
                                            moreImgPath = resource.data.toString()
                                        } else {
                                            moreImgPath = moreImgPath + "," + resource.data
                                        }
                                        morePathList.add(resource.data.toString())

                                        Log.e("imgpath", moreImgPath)
                                        Log.e("imgpath", morePathList.size.toString())

                                    }
                                }

                        }
                    }
                }

                override fun onCancel() {
                }

            })
    }

    private fun getPath(path: String): String {
        if (!path.isEmpty()) {
            val uri = Uri.parse(path)
            val proj =
                arrayOf(MediaStore.Images.Media.DATA)
            val actualimagecursor: Cursor =
                contentResolver.query(uri, proj, null, null, null)!!
            val actual_image_column_index =
                actualimagecursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA)
            actualimagecursor.moveToFirst()
            val img_path = actualimagecursor.getString(actual_image_column_index)
            return img_path
        }
        return ""
    }

    inner class PicAdapter : BaseAdapter() {
        private var mUris: List<Uri>? = null
        private var mPaths: List<String>? = null
        fun setData(uris: List<Uri>?, paths: List<String>?) {
            mUris = uris
            mPaths = paths
            notifyDataSetChanged()
        }

        fun setData() {
            notifyDataSetChanged()
        }

        override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
            val view: View?
            val viewHolder: ViewHolder

            if (convertView == null) {
                val inflater = getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
                // 需要创建视图 animals_list
                view = inflater.inflate(R.layout.item_grid_picture, null)
                viewHolder = ViewHolder(view)
                view?.tag = viewHolder

            } else {
                view = convertView
                viewHolder = view.tag as ViewHolder
            }

            if (position < mData.size) {
                loadImage(mData[position], viewHolder.imgUrl!!)
                Log.i("uri", mData[position])
                viewHolder.deleteImg!!.visibility = View.VISIBLE
            } else {
                loadImage(R.mipmap.icon_add_img_publish_baseinfo, viewHolder.imgUrl!!)
                Log.i("size + ", "走了")
                viewHolder.deleteImg!!.visibility = View.GONE
            }
            viewHolder.deleteImg!!.setOnClickListener {
                mData.removeAt(position)
//                mDataPath.removeAt(position)
                notifyDataSetChanged()
                morePathList.clear()
                if (mData.size > 0) {
                    moreImgPath = ""
                    for (i in mData) {
                        moreImgPath += "$i,"
                    }
                    moreImgPath = moreImgPath.substring(0, moreImgPath.length - 1)
//                    morePathList.addAll(mData)
                } else {
                    moreImgPath = ""

                }

            }

            viewHolder.imgUrl!!.setOnClickListener {
                if (position == mData.size) {
                    //addMainPicture()
//                    SelectUpdatePic()
                    transferPhoto()
                } else {//这里可以添加查看大图的逻辑
                    /*Intent intent = new Intent(parent.getContext(), FriendCircleReleaseActivity.class);
                    intent.putExtra("position", position);
                    intent.putStringArrayListExtra("urlList", mData);
                    startActivity(intent);*/
                }
            }

            if (position < mData.size) {

            }
            return view as View
        }

        override fun getItem(position: Int): Any {
            return mData.get(position)
        }

        override fun getItemId(position: Int): Long {
            return position.toLong()
        }

        override fun getCount(): Int {
            return if (mData.size < 3) {
                if (mData == null) 0 else mData.size + 1
            } else {
                if (mData == null) 0 else mData.size
            }
        }

        private inner class ViewHolder(view: View?) {
            var imgUrl: RadiusImageView? = null
            var deleteImg: ImageView? = null

            init {
                this.imgUrl = view?.findViewById(R.id.img_url)
                this.deleteImg = view?.findViewById(R.id.delete_picture)
            }
        }
    }
}